<template>
  <div id="fleetStatistics" class="list">
    <div class="breadcrumb">
			<Breadcrumb separator=">">
				<BreadcrumbItem to="">车队视图</BreadcrumbItem>
				<BreadcrumbItem to="/fleet/statistics">车队统计</BreadcrumbItem>
			</Breadcrumb>
		</div>

    <TableSearch>
      <Form :label-width="80">
        <Row :gutter="16">
          <Col :md="8">
            <ButtonGroup style="width:60%;">
              <Button type="ghost" @click="changeType('date')" :class="{'active':searchType==='date'}" style="width:50%;">日</Button>
              <Button type="ghost" @click="changeType('month')" :class="{'active':searchType==='month'}" style="width:50%;">月</Button>
            </ButtonGroup>
          </Col>
          <Col :md="8">
            <FormItem label="统计日期">
              <Row>
                <Col :md="10"><DatePicker v-model="searchForm.sTime" :type="searchType" :options="sTimeOption" :editable="false" :clearable="false" placeholder="开始日期" style="width:100%;"></DatePicker></Col>
                <Col :md="4"><div style="text-align:center;">至</div></Col>
                <Col :md="10"><DatePicker v-model="searchForm.eTime" :type="searchType" :options="eTimeOption" :editable="false" :clearable="false" placeholder="结束日期" style="width:100%;"></DatePicker></Col>
              </Row>
		        </FormItem>
          </Col>
          <Col v-if="tabflag==='0'" :md="8">
            <FormItem label="选择小组">
              <Select v-model="tableForm.teamid" placeholder="请选择小组" clearable>
                <Option :value="1">A组</Option>
                <Option :value="2">B组</Option>
                <Option :value="3">C组</Option>
                <Option :value="4">D组</Option>
              </Select>
		        </FormItem>
          </Col>
        </Row>
      </Form>
			<Button type="primary" class="search-btn" icon="search" @click="" long>查询</Button>
		</TableSearch>

    <div class="main">
      <Tabs type="card" v-model="tabflag" :animated="false">
        <div slot="extra">
          <div v-if="tabflag==='0'" class="list-desc">
            <div class="desc-item">
              平均安全指数：<span class="num">78</span>
            </div>
            <div class="desc-item">
              行驶里程合计：<span class="num">78323公里</span>
            </div>
            <div class="desc-item">
              行驶时长合计：<span class="num">983232小时54分钟</span>
            </div>
          </div>
          <div v-if="tabflag==='1'" class="chart-desc">
            <label class="ivu-form-item-label" style="width: 150px;">选择小组（可多选）：</label>
            <CheckboxGroup v-model="chartForm.teamids" @on-change="changeTeam">
              <Checkbox v-for="(v,i) in teamList" :label="v" :key="`team-list-${i}`"></Checkbox>
            </CheckboxGroup>
          </div>
        </div>
        <TabPane name="0" label="统计表">
          <div class="table-content">
						<div class="table" style="margin:0;">
							<table>
								<thead>
									<th>统计日期</th>
									<th>车队</th>
									<th>安全指数</th>
									<th>行驶里程</th>
									<th>行驶时长</th>
								</thead>
								<tbody>
									<tr v-for="(v,i) in [0,1,2,3,4,5,6,7,8,9]" :key="`fleet-statistics-list-${i}`">
										<td>2018-06-01</td>
                    <td>A组</td>
										<td>78</td>
										<td>323公里</td>
										<td>134小时46分钟</td>
									</tr>
								</tbody>
							</table>
						</div>
					</div>
          <Spin size="large" fix v-if="isLoading"></Spin>
        </Tabpane>
        <TabPane name="1" label="趋势图">
          <Card :bordered="false" dis-hover>
            <p slot="title">安全指数</p>
            <div id="safetyRateChart" style="height:240px;"></div>
          </Card>
          <Card :bordered="false" dis-hover>
            <p slot="title">行驶里程</p>
            <div id="driveMileageChart" style="height:240px;"></div>
          </Card>
          <Card :bordered="false" dis-hover>
            <p slot="title">行驶时长</p>
            <div id="driveDurationChart" style="height:240px;"></div>
          </Card>
        </Tabpane>
      </Tabs>
    </div>

  </div>
</template>
<style lang="less" src="@/assets/styles/fleet/fleet-statistics.less"></style>

<script>
  import moment from 'moment'
  import unit   from '@/util/unit'
  import EChart from '@/plugin/EChart'

  export default {
    data(){
      return {
        tabflag:'0',  // 0=统计表，1=趋势图
        searchType:'date',
        searchForm:{
          sTime:moment(moment().subtract(30,'d').format('YYYY-MM-DD')).toDate(),
          eTime:moment(moment().subtract( 1,'d').format('YYYY-MM-DD')).toDate()
        },
        tableForm:{teamid:''},
        chartForm:{
          teamids:['A组','B组','C组','D组']
        },

        safetyRateChart:null,   // 安全指数报表
        driveMileageChart:null, // 行驶里程报表
        driveDurationChart:null,// 行驶时长报表

        teamList:['A组','B组','C组','D组'], // 正式用计算属性
        isLoading:false,
      };
    },
    watch:{
      tabflag(v){
        if (v==='1'){
          this.$nextTick(() => {
            this.createSafetyRateChart();
            this.createDriveMileageChart();
            this.createDriveDurationChart();
          });
        }
      }
    },
    computed:{
      sTimeOption(){
        let t = this.searchType;
        if (t === 'date'){
          return {
            disabledDate:(d) => {
              let max = moment(this.searchForm.eTime||moment().toDate()).toDate();
              let min = moment(this.searchForm.eTime||'1900-01-01').subtract(30,'d').toDate();
              return min >= d || d > max;
            }
          };
        }else{
          return {
            disabledDate:(d) => {
              let max = moment(this.searchForm.eTime||moment().toDate()).toDate();
              let min = moment(moment(this.searchForm.eTime).format('YYYY-MM')).subtract(5,'M').toDate();
              return min > d || d > max;
            }
          };
        }
      },
      eTimeOption(){
        let t = this.searchType;
        if (t === 'date'){
          return {
            disabledDate:(d) => {
              let max = moment(moment().format('YYYY-MM-DD')).subtract(1,'d').toDate();
              let mmax = moment(this.searchForm.sTime).add(30,'d').toDate();
              max = max <= mmax ? max : mmax;
              let min = moment(this.searchForm.sTime).toDate();
              return !(d >= min && d <= max);
            }
          };
        }else{
          return {
            disabledDate:(d) => {
              let max = moment(moment().format('YYYY-MM')).toDate();
              let mmax = moment(this.searchForm.sTime).add(5,'M').toDate();
              max = max <= mmax ? max : mmax;
              let min = moment(moment(this.searchForm.sTime).format('YYYY-MM')).toDate();
              return !(d >= min && d <= max);
            }
          };
        }
      },

    },
    methods:{
      moment,
      time:unit.time,
      changeType(v){
        this.searchType = v;
      },
      createSafetyRateChart(){
        if (this.safetyRateChart) return;
        this.safetyRateChart = new EChart('safetyRateChart',{
          title:{show:false},
          toolbox:{show:false},
          grid:{x:40,y:10,right:0,bottom:50},
          tooltip : {
            trigger: 'axis'
          },
          legend: {show:false,right:0,data:this.teamList},
          xAxis: {
            type: 'category',
            axisLabel:{interval:0,rotate:45},
            data: (function(){
              let lst = [];
              for (let i = 30; i >= 1; i--){
                let m = moment().subtract(i,'d').format('M月D日');
                lst.push(m);
              }
              return lst;
            })()
          },
          yAxis: {type:'value',splitNumber:7,min:0},
          series: (() => {
            let list = [];
            this.teamList.forEach(o => {
              let item = {
                name: o,type: 'line',smooth: true,stack:'safetyRate',
                data: (function(){
                  var res = [];
                  for (let i = 0; i < 30; i++){
                    res.push(Math.floor(Math.random()*12)+1);
                  }
                  return res;
                })()
              };
              list.push(item);
            });
            return list;
          })()
        });
      },
      createDriveMileageChart(){
        if (this.driveMileageChart) return;
        this.driveMileageChart = new EChart('driveMileageChart',{
          title:{show:false},
          toolbox:{show:false},
          // color:['#FFC000','#FF6600','#376092','#9E6A93','#4BACC6'],
          grid:{x:40,y:10,right:0,bottom:50},
          tooltip : {
            trigger: 'axis'
          },
          legend: {
            show:false,right:0,data:this.teamList
          },
          xAxis:[
            {
              type: 'category',
              axisLabel:{interval:0,rotate:45},
              data: (function(){
                let lst = [];
                for (let i = 30; i >= 1; i--){
                  let m = moment().subtract(i,'d').format('M月D日');
                  lst.push(m);
                }
                return lst;
              })()
            }
          ],
          yAxis:[
            {type:'value',splitNumber:7,min:0},
          ],
          series:(() => {
            let list = [];
            this.teamList.forEach(o => {
              let item = {
                name: o,type: 'bar',stack: 'DriveMileage',barWidth:'50%',
                data: (function(){
                  var res = [];
                  for (let i = 0; i < 30; i++){
                    res.push(Math.floor(Math.random()*500)+1);
                  }
                  return res;
                })()
              };
              list.push(item);
            });
            return list;
          })()
        });
      },
      createDriveDurationChart(){
        this.driveDurationChart = new EChart('driveDurationChart',{
          title:{show:false},
          toolbox:{show:false},
          // color:['#FFC000','#FF6600','#376092','#9E6A93','#4BACC6'],
          grid:{x:40,y:10,right:0,bottom:50},
          tooltip: {
            trigger: 'axis',
            formatter:(params)=>{
              let tooltiphtml = '';
              let xname = params[0].axisValue;
              tooltiphtml += `${xname}<br/>行驶时长`;
              params.forEach(o => {
                let time = this.time(o.data,2,2);
                tooltiphtml += `<br/><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${o.color};"></span>${o.seriesName}：${time}`;
              });
              return tooltiphtml;
            }
          },
          legend: {
            show:false,right:0,data:this.teamList
          },
          xAxis:[
            {
              type: 'category',
              axisLabel:{interval:0,rotate:45},
              data: (function(){
                let lst = [];
                for (let i = 30; i >= 1; i--){
                  let m = moment().subtract(i,'d').format('M月D日');
                  lst.push(m);
                }
                return lst;
              })()
            }
          ],
          yAxis:[
            {type:'value',splitNumber:7,min:0},
          ],
          series:(() => {
            let list = [];
            this.teamList.forEach(o => {
              let item = {
                name: o,type: 'bar',stack: 'DriveDuration',barWidth:'50%',
                data: (function(){
                  var res = [];
                  for (let i = 0; i < 30; i++){
                    res.push(Math.floor(Math.random()*500)+1);
                  }
                  return res;
                })()
              };
              list.push(item);
            });
            return list;
          })()
        });
      },
      changeTeam(v){
        let selected = {};
        this.teamList.forEach(o => {
          selected[o] = v.some(oo => oo === o);
        });
        this.$nextTick(() => {
          this.safetyRateChart.updateLegendselected(selected);
          this.driveMileageChart.updateLegendselected(selected);
          this.driveDurationChart.updateLegendselected(selected);
        });
      }
    },
    destroyed(){
      if (this.safetyRateChart)    this.safetyRateChart.dispose();
      if (this.driveMileageChart)  this.driveMileageChart.dispose();
      if (this.driveDurationChart) this.driveDurationChart.dispose();
    }
  }
</script>
